﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Abp.AspNetCore.Mvc.Extensions;
using FwProject.Controllers;
using FwProject.Core.Restaurant;
using FwProject.Distribution;
using FwProject.Distribution.Dto;
using FwProject.PrePaymentInfo;
using FwProject.PrePaymentInfo.Dto;
using FwProject.Settlement;
using FwProject.Settlement.Dto;
using FwProject.Users;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace FwProject.Web.Mvc.Controllers
{
    public class ReceiptController : FwProjectControllerBase
    {
        private readonly IReceiptInfoAppService _receiptInfoAppService;
        private readonly IDistributionAppService _distributionAppService;
        private readonly IDistributionDetailsAppService _distributionDetailsAppService;
        private readonly ISettlementInfoAppService _settlementInfoAppService;
        private readonly ISettlementAccountAppService _settlementAccountAppService;
        private readonly IPaymentInfoAppService _paymentInfoAppService;
        private readonly IUserAppService _userAppService;
        private readonly IHostingEnvironment _env;
        private readonly IDistributionLineAppService _distributionLineAppService;
        public ReceiptController(IReceiptInfoAppService receiptInfoAppService, IDistributionAppService distributionAppService, ISettlementInfoAppService settlementInfoAppService, ISettlementAccountAppService settlementAccountAppService, IUserAppService userAppService, IDistributionDetailsAppService distributionDetailsAppService, IPaymentInfoAppService paymentInfoAppService, IHostingEnvironment env, IDistributionLineAppService distributionLineAppService)
        {
            _receiptInfoAppService = receiptInfoAppService;
            _distributionAppService = distributionAppService;
            _settlementInfoAppService = settlementInfoAppService;
            _settlementAccountAppService = settlementAccountAppService;
            _userAppService = userAppService;
            _distributionDetailsAppService = distributionDetailsAppService;
            _paymentInfoAppService = paymentInfoAppService;
            _env = env;
            _distributionLineAppService = distributionLineAppService;
        }
        /// <summary>
        /// 收款单
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Index(int pageIdx, int size, long? AgentPeoperUserId, long? PaymentPerson, DateTime? ReceiptBeginTime, DateTime? ReceiptEndTime, DateTime? PaymentBeginTime, DateTime? PaymentEndTime, ReceiptInfoStatus? ReceiptInfoStatus, string ReceiptInfoNumber = "", string RestaurantName = "")
        {
            if (pageIdx == 0)
                pageIdx = 1;

            if (size == 0)
                size = 20;
            if (Request.IsAjaxRequest())
            {
                var model = await _receiptInfoAppService.GetPagedListAsync(pageIdx, size, ReceiptBeginTime, ReceiptEndTime, PaymentBeginTime, PaymentEndTime, AgentPeoperUserId, PaymentPerson, ReceiptInfoNumber, RestaurantName, ReceiptInfoStatus);
                return PartialView("IndexPartial", model);
            }
            return View();
        }

        public async Task<IActionResult> ExportExcel(long? AgentPeoperUserId, long? PaymentPerson, DateTime? ReceiptBeginTime, DateTime? ReceiptEndTime, DateTime? PaymentBeginTime, DateTime? PaymentEndTime, ReceiptInfoStatus? ReceiptInfoStatus, string ReceiptInfoNumber = "", string RestaurantName = "")
        {
            var list = await _receiptInfoAppService.GetAllListAsync(ReceiptBeginTime, ReceiptEndTime, PaymentBeginTime, PaymentEndTime, AgentPeoperUserId, PaymentPerson, ReceiptInfoNumber, RestaurantName, ReceiptInfoStatus);

            return DoExcel<ReceiptInfoDto>(list, _env);
        }

        /// <summary>
        /// 创建收款单
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Create()
        {
            var list = await _settlementAccountAppService.GetAllSettlementAccountAsync();
            ViewBag.Account = list.Select(o => new SelectListItem() { Value = o.Id.ToString(), Text = o.Name });

            return View(new ReceiptInfoEnterDto());
        }

        [HttpPost]
        public async Task<IActionResult> Create(ReceiptInfoEnterDto input)
        {
            var id = await _receiptInfoAppService.Create_Management(input);
            return Json("suggest");
        }

        /// <summary>
        /// 选择应收单据
        /// </summary>
        /// <param name="id">餐厅Id</param>
        /// <returns></returns>
        public async Task<IActionResult> SelectSettlement(Guid id)
        {
            var data = await _settlementInfoAppService.GetSettlementInfoByRestaurantIdAsync(id);
            return View(data);
        }

        /// <summary>
        /// 快速收款
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> FastlyReceipt(int pageIdx, int size, BalanceWayEnum? BalanceWay, BalanceCycleEnum? BalanceCycle, Guid? Line, long? DriverId, string RestaurnatName = "")
        {
            var user = await _userAppService.GetAllAgentPeoperAsync();
            ViewBag.User = user;
            var account = await _settlementAccountAppService.GetAllSettlementAccountAsync();
            ViewBag.Account = account;

            if (pageIdx == 0)
                pageIdx = 1;

            if (size == 0)
                size = 20;

            var lines = await _distributionLineAppService.GetAllLineAsync();
            ViewBag.Line = lines.Select(o => new SelectListItem() { Value = o.Id.ToString(), Text = o.LineName });


            var model = await _settlementInfoAppService.GetReceiptFastlyListAsync(pageIdx, size, RestaurnatName, BalanceWay, BalanceCycle, Line, DriverId);

            if (Request.IsAjaxRequest())
            {
                return PartialView("FastlyReceiptPartial", model);
            }
            return View(model);
        }

        public async Task<IActionResult> QuickReceipt(QuickReceiptListOutput input)
        {
            await _receiptInfoAppService.QuickReceipt(input);
            return Json(1);
        }

        /// <summary>
        /// 应收明细
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> ReceivableDetails(int pageIdx, Guid id, DateTime? beginTime, DateTime? endTime)
        {
            if (pageIdx == 0)
                pageIdx = 1;
            ViewBag.Id = id;
            if (Request.IsAjaxRequest())
            {
                var model = await _settlementInfoAppService.GetReceivableDetailsAsync(pageIdx, 20, id, beginTime, endTime);
                return PartialView("ReceivableDetailsPartial", model);
            }
            return View();
        }
        /// <summary>
        /// 收据详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> SettlementDetails(Guid id)
        {
            var settlement = _settlementInfoAppService.GetById(id);

            var details = await _distributionDetailsAppService.GetDistributionDetailsBySettlementIdAsync(id);

            Tuple<SettlementInfoDto, List<DistributionDetailsOutInputDto>> model = new Tuple<SettlementInfoDto, List<DistributionDetailsOutInputDto>>(settlement, details);

            return View(model);
        }
        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> ToExamine(Guid id, SettlementInfoInput input)
        {
            await _settlementInfoAppService.Check(id, input);
            return Json("0");
        }
        /// <summary>
        /// 反审核
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> AntiCheck(Guid id)
        {
            await _settlementInfoAppService.AntiCheck(id);
            return Redirect("/Receipt/SettlementDetails?id=" + id);
        }
        /// <summary>
        /// 收款单详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> ReceiptDetail(Guid id)
        {
            var receipt = _receiptInfoAppService.GetById(id);

            var account = await _settlementAccountAppService.GetByIdAsync(receipt.CapitalAccountId);
            ViewBag.Account = account.Name;
            var settlement = await _settlementInfoAppService.GetSettlementInfoByReceiptInfoIdAsync(id);

            Tuple<ReceiptInfoDto, List<SettlementInfoDto>> tuple = new Tuple<ReceiptInfoDto, List<SettlementInfoDto>>(receipt, settlement);

            return View(tuple);
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<IActionResult> Save(Guid id, ReceiptInfoInput input)
        {
            await _receiptInfoAppService.Update(id, input);
            return Json(1);
        }
        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> ReceiptSubmit(Guid id)
        {
            await _receiptInfoAppService.Submit(id);
            return Redirect("/Receipt/ReceiptDetail?id=" + id);
        }
        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> ReceiptExamine(Guid id)
        {
            await _receiptInfoAppService.Examine(id);
            return Redirect("/Receipt/ReceiptDetail?id=" + id);
        }
        /// <summary>
        /// 缴款作废
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult ReceiptAnTiExamine(Guid id)
        {
            _paymentInfoAppService.ToVoid(id);
            return Redirect("/Receipt/Create");
        }

        /// <summary>
        /// 反审核
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult ReceiptAntiaudit(Guid id)
        {
            _paymentInfoAppService.Antiaudit(id);
            return Redirect("/Receipt/ReceiptDetail?id=" + id);
        }
    }
}